import resolve from '@rollup/plugin-node-resolve';
import terser from '@rollup/plugin-terser';
import replace from '@rollup/plugin-replace';
import livereload from 'rollup-plugin-livereload';
import serve from 'rollup-plugin-dev-server';
import html from '@rollup/plugin-html';
import minimist from 'minimist';
import * as cardsConfig from './cards.config.js';

const argv = minimist(process.argv.slice(2));

const isDev = argv['env'] === 'development';
const card = argv['card'];

const entries = {};

const getFilePathByName = name => `./src/${name}/${name}.js`;
const getExamplesPathByName = name => `./src/${name}/examples.js`;
const cardIsExist = (name) => !!cardsConfig[name]; // 卡片是否存在

// 判断卡片是否存在
if (card && !cardIsExist(card)) {
  throw new Error('卡片不存在');
}

if (card) {
  entries[`${card}${!isDev ? `-v${cardsConfig[card]}` : ''}`] = getFilePathByName(card);
} else {
  for (let i in cardsConfig) {
    entries[`${i}${!isDev ? `-v${cardsConfig[i]}` : ''}`] = getFilePathByName(i);
  }
}

function lowerCamelToKebab(str) {
  return str.replace(/([A-Z])/g, '-$1').toLowerCase();
}

const plugins = [
  replace({
    values: {
      'TAG_NAME': filename => `kp-${lowerCamelToKebab(filename.replace(/.js$/, ''))}`
    }
  }),
];

if (isDev) {
  if (card) {
    const examples = (await import(getExamplesPathByName(card))).default;
    plugins.push(html({
      template: ({ attributes, bundle, files, publicPath, title, scripts }) => {
        const cardContent = examples.map(({ name, attrs }, idx) => {
          return `<h3 class="subtitle">#${idx + 1} ${name || ''}</h3><div class="card"><kp-article ${Object.keys(attrs).map((key) => (typeof(attrs[key]) === 'boolean' ? key : `${key}=${attrs[key]}`)).join(' ')}></kp-article></div>`;
        }).join('');

        return `<!DOCTYPE html>
        <html>
        <head>
          <meta charset="UTF-8">
          <title>${card}</title>
          <style>
            body {
              margin: 0;
              font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji";
            }
            .wrap {
              flex: 1;
              padding: 16px;
              background-color: rgb(254, 252, 248);
              color: #212B36;
            }
            .wrap.dark {
              background-color: rgb(27, 27, 28);
              color: rgb(228, 229, 231);
            }
            .wrap .title {
              margin: 0;
              line-height: 56px;
            }
            .wrap .subtitle {
              margin: 0;
              line-height: 40px;
              color: rgb(154, 155, 157);
            }
            .wrap .card {
              box-sizing: border-box;
              border-radius: 12px;
              padding: 16px;
              width: 100%;
              overflow-x: hidden;
              margin-bottom: 32px;
              background-color: rgb(255, 255, 255);
              border: 1px solid rgb(245, 245, 245);
              --kp-color-primary: #FFB851;
              --kp-color-primary-hover: #DD8923;
              --kp-color-text-primary: #212B36;
              --kp-color-text-secondary: #637381;
              --kp-color-border: #DFE3E8;
              --kp-color-background-paper: #fff;
              --kp-color-background-neutral: #F9FAFB;
            }
            .wrap.dark .card {
              background-color: rgb(30, 32, 34);
              border: 1px solid rgb(47, 49, 56);
              --kp-color-primary: #DD8923;
              --kp-color-primary-hover: rgb(154, 95, 24);
              --kp-color-text-primary: rgb(228, 229, 231);
              --kp-color-text-secondary: rgb(154, 155, 157);
              --kp-color-border: rgb(47, 49, 56);
              --kp-color-background-paper: rgb(30, 32, 34);
              --kp-color-background-neutral: #2b2d34;
            }
          </style>
          <script type="importmap">{"imports": {"lit": "//assets.kiipu.com/libs/lit/3.1.3/lit-all.min.js", "card-ui": "//assets.kiipu.com/libs/card-ui/0.0.8/all.min.js"}}</script>
        </head>
        <body>
          <div style="display: flex">
            <div class="wrap"><h2 class="title">Light</h2>${cardContent}</div>
            <div class="wrap dark"><h2 class="title">Dark</h2>${cardContent}</div>
          </div>
          ${Object.keys(bundle).map(i => `<script type="module" src="${i}"></script>`).join('')}
        </body>
        </html>`
      }
    }));
  }

  plugins.push(serve({
    port: 9997,
    contentBase: ['dist/'],
    headers: {
      'Access-Control-Allow-Origin': 'http://localhost:8080',
      'Access-Control-Allow-Credentials': true,
      'Access-Control-Expose-Headers': 'Access-Control-Expose-Headers'
    },
    allowCrossOrigin: true,
  }));

  plugins.push(livereload({
    watch: 'dist',
  }));
} else {
  plugins.push(terser());
}

export default {
  input: entries,
  plugins: [resolve()],
	output: {
    dir: './dist',
    entryFileNames: ({ name }) => `${lowerCamelToKebab(name)}.js`,
    format: 'es',
    plugins,
	},
};
